<template>
  <div id="app">
    <van-nav-bar title="临期" fixed/>

    <van-notice-bar
      left-icon="volume-o"
      :text="text[Math.floor(Math.random() * 5)]"
    />

    <div id="color-change" class="mid-remind-up">熊霸天下提醒您</div>
    <div class="mid-remind-down" id="red-font">
      以下物品保质期不足 7 天！！！
    </div>

    <van-cell-group inset>
      <van-swipe-cell v-for="(item, index) in idarr" :key="index">
        <div class="text-son" v-if="timearr[index] < 8">
          <van-card
            :title="namearr[index]"
            centered
            class="goods-card"
            v-if="imgarr[index]"
            :thumb="imgarr[index].url()"
            @click="goToItemPage(item)"
          >
            <template #tags>
              <p id="dao-ji-shi">还有{{ timearr[index] }}天过期</p>
            </template>
          </van-card>

          <van-card
            :title="namearr[index]"
            centered
            class="goods-card"
            v-else
            thumb="https://img.3dmgame.com/uploads/allimg/161212/346_161212150216_1_lit.gif"
            @click="goToItemPage(item)"
          >
            <template #tags>
              <p id="dao-ji-shi">还有{{ timearr[index] }}天过期</p>
            </template>
          </van-card>

          <van-progress
            color="#f2826a"
            stroke-width="10"
            :percentage="
              Math.ceil(
                dayarr[index] ? (1 - timearr[index] / dayarr[index]) * 100 : 100
              )
            "
          />
        </div>
      </van-swipe-cell>
    </van-cell-group>
    <div id="addOne">
      <van-button round type="primary" @click="showPopup"
        >添加新的物品</van-button
      >
    </div>

    <van-popup v-model="show">
      <van-form @submit="onSubmit">
        <van-field
          v-model="item"
          name="物品名"
          label="物品名"
          placeholder="物品名"
          :rules="[{ required: true, message: '请填写物品名' }]"
        />

        <van-field
          readonly
          clickable
          label="生产日期"
          :value="currentDateView"
          placeholder="选择日期"
          @click="showTimePicker = true"
        />
        <van-popup v-model="showTimePicker" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="生产日期"
            :min-date="minDate"
            :max-date="maxDate"
            @cancel="showTimePicker = false"
            @confirm="onTimeConfirm"
          />
        </van-popup>

        <van-field
          v-model="shelfLife"
          name="保质期"
          label="保质期"
          type="digit"
          placeholder="单位：天"
          :rules="[{ required: true, message: '请填写保质期' }]"
        />

        <van-field
          readonly
          clickable
          name="picker"
          :value="value"
          label="标签"
          placeholder="选择标签"
          @click="showPicker = true"
        />

        <div class="mid">
          <van-uploader :after-read="afterRead">
            <van-button
              round
              icon="plus"
              color="linear-gradient(to right, #ff6034, #ee0a24)"
              >上传图片</van-button
            >
          </van-uploader>
        </div>

        <van-popup v-model="showPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="columns"
            @confirm="onConfirm"
            @cancel="showPicker = false"
          />
        </van-popup>

        <div style="margin: 16px">
          <van-button
            round
            block
            @click="submit"
            type="info"
            native-type="submit"
            >提交</van-button
          >
        </div>
      </van-form>
    </van-popup>
  </div>
</template>

<script>
import { AV } from "@/App";

const FoodPeriod = AV.Object.extend("FoodPeriod");

// 构建对象
const foodPeriod = new FoodPeriod();

export default {
  name: "App",
  components: {},

  data() {
    return {
      show: false,
      item: "",
      shelfLife: "",
      value: "",
      columns: ["水果", "药物", "零食", "贵重物品"],
      showPicker: false,
      showTimePicker: false,
      minDate: new Date(1982, 0, 1),
      maxDate: new Date(2095, 10, 1),
      currentDate: new Date(),
      currentDateView: new Date().toLocaleDateString(),
      namearr: [],
      timearr: [],
      idarr: [],
      typearr: [],
      dayarr: [],
      imgarr: [],
      text: [
        "锄禾日当午，汗滴禾下土。谁知盘中餐，粒粒皆辛苦。",
        "谁在平日节衣缩食，在穷困时就容易过难关；谁在富足时豪华奢侈，在穷困时就会死于饥寒。",
        "其实地上本没有路,走的人多了,便成了路。",
        "怀疑并不是缺点。总是疑,而并不下断语,这才是缺点。",
        "横眉冷对千夫指，俯首甘为孺子牛。",
      ],
    };
  },
  created() {
    this.getAllItems();
  },
  methods: {
    getAllItems() {
      this.namearr = [];
      this.timearr = [];
      this.idarr = [];
      this.typearr = [];
      this.dayarr = [];
      this.imgarr = [];
      const query = new AV.Query("FoodPeriod");
      // query.equalTo('Item', '香蕉');
      query.find().then((students) => {
        students.forEach((itemson) => {
          const ID = itemson.id;
          const img1 = itemson.get("img");
          const Type = itemson.get("Type");
          const name = itemson.get("Item"); //名字
          const timeStart = itemson.get("Start"); //开始日期
          const timeEnd = itemson.get("Deadline"); //结束日期
          const day = itemson.get("ShelfLife"); //保质期
          const NumberOfDays = Math.ceil(
            this.getDaysBetween(this.getTime(new Date()), timeEnd)
          ); //相差几天
          this.namearr.push(name);
          this.timearr.push(NumberOfDays);
          this.idarr.push(ID);
          this.typearr.push(Type);
          this.dayarr.push(day);
          this.imgarr.push(img1);
        });

        // console.log(students);
        // students 是包含满足条件的 Student 对象的数组
      });
    },
    showPopup() {
      this.show = true;
    },
    goToItemPage(id) {
      this.$router.push({
        path: "/item",
        query: {
          id: id,
        },
      });
    },
    submit() {
      // 为属性赋值
      if (this.item != "" || this.value !== "") {
        foodPeriod.set("Item", this.item);
        foodPeriod.set("Type", this.value);
        foodPeriod.set("Start", this.getTime(this.currentDate));

        foodPeriod.set(
          "Deadline",
          this.AddDays(this.shelfLife, this.currentDate)
        );
        foodPeriod.set("ShelfLife", this.shelfLife);
        // 将对象保存到云端
        foodPeriod.save().then(
          (foodPeriod) => {
            // 成功保存之后，执行其他逻辑
            console.log(`保存成功。objectId：${foodPeriod.id}`);
            this.show = false;
            this.item = "";
            this.value = "";
            this.shelfLife = "";
            this.getAllItems();
            this.$toast.success("添加成功");
          },
          (error) => {
            // 异常处理
          }
        );
      }
    },

    onSubmit(values) {
      console.log("submit", values);
    },

    onConfirm(value) {
      this.value = value;
      this.showPicker = false;
    },

    onTimeConfirm(currentDate) {
      this.currentDateView = currentDate.toLocaleDateString();
      this.showTimePicker = false;
    },

    afterRead(file) {
      const data = {
        base64: file.content,
      };
      const image = new AV.File(file.file.name, data);
      image
        .save({
          onprogress: (process) => {
            console.log(process);
          },
        })
        .then(
          (file) => {
            console.log(image);
          },
          (error) => {
            window.alert("保存图片失败!");
            throw error;
          }
        );
      console.log(file);
      foodPeriod.set("img", image);
      return image;
      // 此时可以自行将文件上传至服务器
    },

    getTime(date) {
      let y = date.getFullYear(); //年
      let m = date.getMonth() + 1; //月，月是从0开始的所以+1
      let d = date.getDate(); //日
      m = m < 10 ? "0" + m : m; //小于10补0
      d = d < 10 ? "0" + d : d; //小于10补0
      // console.log(y + "-" + m + "-" + d);
      return y + "-" + m + "-" + d; //返回时间形式yyyy-mm-dd
    },

    AddDays(num, num2) {
      var newdate = num2;
      var newtimems = newdate.getTime() + num * 24 * 60 * 60 * 1000;
      newdate.setTime(newtimems);
      var time =
        newdate.getFullYear() +
        "-" +
        (newdate.getMonth() + 1) +
        "-" +
        newdate.getDate();
      return time;
    },

    getDaysBetween(date1, date2) {
      var startDate = Date.parse(date1);
      var endDate = Date.parse(date2);
      if (startDate > endDate) {
        return 0;
      }
      if (startDate == endDate) {
        return 1;
      }
      var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
      return days;
    },
  },
};
</script>

<style>
.van-notice-bar {
  margin-top: 60px;
}
.van-nav-bar__content {
  padding-block: 7px;
  background-color: #e9eaec;
}

.van-nav-bar__title {
  font-weight: 1000;
  font-size: 16px;
}
.text-son {
  margin-bottom: 20px;
}

.mid {
  padding-block: 20px;
  display: flex;
  justify-content: center;
}

.mid-remind-up {
  padding-top: 10px;
  display: flex;
  justify-content: center;
}

.mid-remind-down {
  padding-bottom: 10px;
  display: flex;
  justify-content: center;
}

.van-popup {
  border-radius: 10px;
}

#addOne {
  position: fixed;
  bottom: 75px;
  left: 50%;
  transform: translateX(-50%);
}

#app {
  margin-bottom: 60px;
}

#color-change {
  animation: changeColor 2s linear 0s infinite;
}

@keyframes changeColor {
  0% {
    color: #333;
  }
  25% {
    color: rgb(255, 0, 234);
  }
  50% {
    color: rgb(98, 0, 255);
  }
  75% {
    color: rgb(0, 255, 21);
  }
  100% {
    color: rgb(18, 18, 18);
  }
}

#red-font {
  color: rgb(248, 1, 1);
}

.van-card__num {
  color: #969799;
}

.van-card__title {
  line-height: 40px;
  font-size: large;
  display: flex;
  justify-content: center;
}

.van-card__desc {
  line-height: 40px;
  font-size: small;
  padding-left: 160px;
  max-height: 25px;
  margin-top: 40px;
}

#dao-ji-shi {
  display: flex;
  justify-content: center;
}
</style>

